package com.smartlink.app.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.smartlink.app.R;
import com.smartlink.app.adapter.GridItemAdapter;
import com.smartlink.app.common.Constant;
import com.smartlink.app.pojo.Info;
import com.smartlink.app.util.GpsUtils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class OutDoorFragment extends Fragment {

    private TextView tv_out_door_address, tv_out_door_temperature, tv_out_door_date;
    private GridView gv_out_door_grid;
    private GridItemAdapter gridItemAdapter;
    int[] images = {R.drawable.shi_du, R.drawable.yu_liang, R.drawable.feng_li, R.drawable.feng_xiang, R.drawable.ya_qiang, R.drawable.pm25};
    private String[] titles = {"湿度", "降雨量", "风力", "风向", "大气压", "PM2.5"};
    private String[] values = {"0", "0", "0", "0", "0", "0"};

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 0x1:
                    //更新天气数据
                    Info info = (Info) msg.obj;
                    values[0] = info.getHumidity();
                    values[1] = info.getRain();
                    values[2] = info.getWindpower();
                    values[3] = info.getWinddirect();
                    values[4] = info.getAirpressure();
                    tv_out_door_temperature.setText(info.getTemperature() + "℃");
                    break;
                case 0x2:
                    //更新pm2.5
                    String pm = (String) msg.obj;
                    values[5] = pm;
                    break;
                case 0x3:
                    //更新城市名称
                    String cityName = (String) msg.obj;
                    tv_out_door_address.setText(cityName);
                    break;
                case 0x4:
                    //环境云无法获取数据
                    Toast.makeText(getContext(), "部分数据暂时无法获取，请稍后刷新再试", Toast.LENGTH_SHORT).show();
                    break;
            }
            gridItemAdapter.notifyDataSetChanged();
            super.handleMessage(msg);
        }
    };

    public OutDoorFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_out_door, container, false);
        bindView(rootView);
        return rootView;
    }

    /**
     * 绑定视图
     *
     * @param rootView
     */
    private void bindView(View rootView) {
        tv_out_door_address = (TextView) rootView.findViewById(R.id.tv_out_door_address);
        tv_out_door_date = (TextView) rootView.findViewById(R.id.tv_out_door_date);
        tv_out_door_temperature = (TextView) rootView.findViewById(R.id.tv_out_door_temperature);
        gv_out_door_grid = (GridView) rootView.findViewById(R.id.gv_out_door_grid);
        gridItemAdapter = new GridItemAdapter(getContext(), titles, values, images);
        gv_out_door_grid.setAdapter(gridItemAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        setDate();
        updateWeather();
    }

    private void setDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String date = sdf.format(new Date());
        tv_out_door_date.setText(date);
    }


    public void updateWeather() {
        GpsUtils gpsUtils = GpsUtils.getInstance(getContext());
        double[] lanLon = gpsUtils.getValues();
        int radius = 20;
        AsyncHttpClient client = new AsyncHttpClient();
        HttpEntity entity = null;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("accessId", Constant.ENVICLOUD.ENVICLOUD_AK);
            jsonObject.put("center_lat", lanLon[0]);
            jsonObject.put("center_lng", lanLon[1]);
            jsonObject.put("radius", radius);
            entity = new StringEntity(jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        client.post(getContext(), Constant.ENVICLOUD.ENVICLOUD_URL_GETCITYCODE, entity, "application/json", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String body = new String(bytes);

                try {
                    JSONObject jsonObject = new JSONObject(body);
                    JSONArray jsonArray = (JSONArray) jsonObject.get("info");
                    JSONObject cityJson = (JSONObject) jsonArray.get(0);
                    String cityName = cityJson.getString("countyname_cn");
                    String cityCode = cityJson.getString("citycode");
                    //发送更新城市名称
                    Message msg = handler.obtainMessage();
                    msg.what = 0x3;
                    msg.obj = cityName;
                    handler.handleMessage(msg);
                    //查询天气状况
                    getWeatherCurrent(cityCode);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });


    }

    /**
     * 根据CITY  code获取天气情况
     *
     * @param cityCode
     */
    public void getWeatherCurrent(String cityCode) {

        String path = Constant.ENVICLOUD.ENVICLOUD_URL_GETWEATHERCURRENT +
                "citycode=" + cityCode + "&ak=" + Constant.ENVICLOUD.ENVICLOUD_AK;

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

        asyncHttpClient.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String body = new String(responseBody);
                try {

                    //获取json
                    JSONObject jsonObject = new JSONObject(body);
                    String resultCode = jsonObject.getString("resultCode");
                    if ("0".equals(resultCode)) {
                        //获取json中的info对应的json
                        JSONObject jsonInfo = (JSONObject) jsonObject.get("info");
                        //获取具体的天气状况
                        Gson gson = new Gson();
                        Info info = gson.fromJson(jsonInfo.toString(), Info.class);
                        //更新界面
                        Message message = handler.obtainMessage();
                        message.obj = info;
                        message.what = 0x1;
                        handler.sendMessage(message);
                    } else {
                        handler.obtainMessage(0x4).sendToTarget();

                    }

                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

        //获取pm2.5
        String pathRealtimeair = Constant.ENVICLOUD.ENVICLOUD_URL_GETREALTIMEAIR + "citycode=" + cityCode + "&ak=" + Constant.ENVICLOUD.ENVICLOUD_AK;
        asyncHttpClient.get(pathRealtimeair, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String body = new String(responseBody);

                try {
                    //获取pm2.5
                    JSONObject jsonObject = new JSONObject(body);
                    String resultCode = jsonObject.getString("resultCode");
                    if ("0".equals(resultCode)) {
                        JSONArray jsonArray = (JSONArray) jsonObject.get("info");
                        JSONObject jsonObject1 = (JSONObject) jsonArray.get(0);
                        String pmvalue = (String) jsonObject1.get("pmvalue");
                        Message message = handler.obtainMessage();
                        message.what = 0x2;
                        message.obj = pmvalue;
                        handler.sendMessage(message);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }

}
